<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <div class="stats-grid">
      <div class="stat-card">
        <div class="stat-icon books">
          <el-icon size="32">
            <Reading />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.totalBooks || 0 }}</div>
          <div class="stat-label">图书总数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon borrowed">
          <el-icon size="32">
            <DocumentCopy />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.borrowedBooks || 0 }}</div>
          <div class="stat-label">已借图书</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon overdue">
          <el-icon size="32">
            <Warning />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.overdueBooks || 0 }}</div>
          <div class="stat-label">逾期图书</div>
        </div>
      </div>

      <div class="stat-card" v-if="userStore.isAdmin">
        <div class="stat-icon users">
          <el-icon size="32">
            <User />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stats.totalUsers || 0 }}</div>
          <div class="stat-label">用户总数</div>
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-grid">
      <!-- 最新图书 -->
      <div class="content-card">
        <div class="card-header">
          <h3>最新图书</h3>
          <el-link type="primary" @click="$router.push('/books')">
            查看更多
          </el-link>
        </div>
        <div class="card-content">
          <div v-if="latestBooks.length === 0" class="empty-state">
            <el-empty description="暂无数据" />
          </div>
          <div v-else class="book-list">
            <div v-for="book in latestBooks" :key="book.id" class="book-item">
              <div class="book-cover">
                <img v-if="book.coverUrl" :src="book.coverUrl" :alt="book.title" />
                <div v-else class="default-cover">
                  <el-icon>
                    <Reading />
                  </el-icon>
                </div>
              </div>
              <div class="book-info">
                <div class="book-title">{{ book.title }}</div>
                <div class="book-author">{{ book.author }}</div>
                <div class="book-category">{{ book.categoryName }}</div>
              </div>
              <div class="book-status">
                <el-tag :type="book.status === 'AVAILABLE' ? 'success' : 'warning'" size="small">
                  {{ book.status === 'AVAILABLE' ? '可借' : '已借' }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 我的借阅 -->
      <div class="content-card">
        <div class="card-header">
          <h3>我的借阅</h3>
          <el-link type="primary" @click="$router.push('/my-borrows')">
            查看更多
          </el-link>
        </div>
        <div class="card-content">
          <div v-if="myBorrows.length === 0" class="empty-state">
            <el-empty description="暂无借阅记录" />
          </div>
          <div v-else class="borrow-list">
            <div v-for="record in myBorrows" :key="record.id" class="borrow-item">
              <div class="borrow-book">{{ record.bookTitle }}</div>
              <div class="borrow-date">{{ formatDate(record.borrowDate) }}</div>
              <div class="borrow-status">
                <el-tag :type="getStatusType(record.status)" size="small">
                  {{ getStatusText(record.status) }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions" v-if="userStore.isAdmin">
      <h3>快捷操作</h3>
      <div class="action-grid">
        <el-button type="primary" size="large" @click="$router.push('/books/add')">
          <el-icon>
            <Plus />
          </el-icon>
          添加图书
        </el-button>

        <el-button type="success" size="large" @click="$router.push('/categories')">
          <el-icon>
            <Collection />
          </el-icon>
          管理分类
        </el-button>

        <el-button type="warning" size="large" @click="$router.push('/borrow-records')">
          <el-icon>
            <List />
          </el-icon>
          借阅管理
        </el-button>

        <el-button type="info" size="large" @click="$router.push('/users')">
          <el-icon>
            <User />
          </el-icon>
          用户管理
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getBorrowStats } from '@/api/borrow'
import { getLatestBooks } from '@/api/book'
import { getMyBorrows } from '@/api/borrow'
import {
  Reading,
  DocumentCopy,
  Warning,
  User,
  Plus,
  Collection,
  List
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 统计数据
const stats = ref({})

// 最新图书
const latestBooks = ref([])

// 我的借阅记录
const myBorrows = ref([])

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString()
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'BORROWED':
      return 'primary'
    case 'RETURNED':
      return 'success'
    case 'OVERDUE':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'BORROWED':
      return '借阅中'
    case 'RETURNED':
      return '已归还'
    case 'OVERDUE':
      return '已逾期'
    default:
      return '未知'
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getBorrowStats()
    stats.value = response.data
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载最新图书
const loadLatestBooks = async () => {
  try {
    const response = await getLatestBooks({ size: 5 })
    latestBooks.value = response.data.records || []
  } catch (error) {
    console.error('加载最新图书失败:', error)
  }
}

// 加载我的借阅记录
const loadMyBorrows = async () => {
  try {
    const response = await getMyBorrows({ size: 5 })
    myBorrows.value = response.data.records || []
  } catch (error) {
    console.error('加载借阅记录失败:', error)
  }
}

// 初始化数据
onMounted(() => {
  loadStats()
  loadLatestBooks()
  loadMyBorrows()
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.stat-icon.books {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.borrowed {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.overdue {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.stat-icon.users {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.content-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.card-content {
  padding: 24px;
  max-height: 400px;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.book-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.book-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  transition: all 0.3s;
}

.book-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.book-cover {
  width: 40px;
  height: 56px;
  border-radius: 4px;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  color: #999;
}

.book-info {
  flex: 1;
}

.book-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-author {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.book-category {
  font-size: 12px;
  color: #999;
}

.borrow-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.borrow-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
}

.borrow-book {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.borrow-date {
  font-size: 12px;
  color: #666;
  margin: 0 12px;
}

.quick-actions {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.quick-actions h3 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }

  .content-grid {
    grid-template-columns: 1fr;
  }

  .action-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  }
}
</style>